<template>
  <div class="order-query-page">
    <!-- 页面标题 -->
    <div class="page-title">订单查询管理</div>

    <!-- 标签切换栏 -->
    <div class="tab-container">
      <div 
        class="tab-item" 
        :class="{ active: activeTab === 'receipt' }"
        @click="switchTab('receipt')"
      >
        收款单查询
      </div>
      <div 
        class="tab-item" 
        :class="{ active: activeTab === 'sales' }"
        @click="switchTab('sales')"
      >
        销售单查询
      </div>
      <el-button 
        type="text" 
        icon="ArrowLeft" 
        class="back-btn"
        @click="handleBack"
      >
        返回列表
      </el-button>
    </div>

    <!-- 筛选区域 -->
    <el-card class="filter-card">
      <div class="filter-row">
        <!-- 日期筛选 -->
        <div class="filter-item">
          <span class="filter-label">{{ activeTab === 'receipt' ? '收款日期' : '销售日期' }}：</span>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="date-picker"
          />
        </div>

        <!-- 关键词搜索 -->
        <div class="filter-item">
          <span class="filter-label">关键词：</span>
          <el-input
            v-model="keyword"
            :placeholder="activeTab === 'receipt' ? '订单号/联系人/手机号' : '订单号/产品名称/门店'"
            class="keyword-input"
            @keyup.enter="fetchTableData"
          />
        </div>

        <!-- 操作按钮 -->
        <div class="filter-actions">
          <el-button 
            type="primary" 
            @click="fetchTableData"
          >
            <Search /> 搜索
          </el-button>
          <el-button 
            type="default" 
            @click="resetFilter"
          >
            重置
          </el-button>
        </div>
      </div>

      <!-- 快捷周期筛选 -->
      <div class="quick-period">
        <span class="period-label">快捷筛选：</span>
        <el-radio-group v-model="activePeriod" @change="handlePeriodChange">
          <el-radio-button label="today">{{ activeTab === 'receipt' ? '今日收款' : '今日销售' }}</el-radio-button>
          <el-radio-button label="week">{{ activeTab === 'receipt' ? '本周收款' : '本周销售' }}</el-radio-button>
          <el-radio-button label="month">{{ activeTab === 'receipt' ? '本月收款' : '本月销售' }}</el-radio-button>
        </el-radio-group>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" style="margin-top: 16px;">
      <el-table
        :data="tableData"
        border
        show-summary
        :summary-method="calculateSummary"
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <!-- 序号 -->
        <el-table-column type="index" label="序号" align="center" />
        
        <!-- 通用列 -->
        <el-table-column prop="shopName" label="门店名称" align="center" />
        <el-table-column 
          :prop="activeTab === 'receipt' ? 'receiptTime' : 'salesTime'" 
          :label="activeTab === 'receipt' ? '收款时间' : '销售时间'" 
          align="center" 
        />
        <el-table-column prop="orderNo" label="订单编号" align="center" />
        <el-table-column prop="contact" label="联系人" align="center" />
        <el-table-column prop="phone" label="手机号" align="center" />
        <el-table-column prop="manager" label="负责人" align="center" />
        
        <!-- 差异列 -->
        <el-table-column 
          :prop="activeTab === 'receipt' ? 'receiptAmount' : 'salesAmount'" 
          :label="activeTab === 'receipt' ? '收款金额' : '销售金额'" 
          align="center" 
        />
        <el-table-column 
          :prop="activeTab === 'receipt' ? 'paymentType' : 'productType'" 
          :label="activeTab === 'receipt' ? '支付方式' : '产品类型'" 
          align="center" 
        />
        <el-table-column 
          :prop="activeTab === 'receipt' ? 'arrears' : 'discount'" 
          :label="activeTab === 'receipt' ? '欠款金额' : '折扣金额'" 
          align="center" 
        />
        
        <!-- 状态列 -->
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <el-tag 
              :type="statusTypeMap[scope.row.status]"
              size="small"
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        
        <!-- 操作列 -->
        <el-table-column label="操作" align="center" width="300" >
          <template #default="scope">
            <el-button 
              type="primary" 
              @click="handleEdit(scope.row)"
              :disabled="scope.row.status === '已冻结'"
              class="oper-btn"
            >
              编辑
            </el-button>
            <el-button 
              type="success" 
              @click="handleDetail(scope.row)"
              class="oper-btn"
            >
              详情
            </el-button>
            <el-button 
              :type="scope.row.status === '已冻结' ? 'info' : 'warning'" 
              @click="handleFreeze(scope.row)"
              class="oper-btn"
            >
              {{ scope.row.status === '已冻结' ? '已冻结' : '冻结' }}
            </el-button>
            <el-button 
              type="danger" 
              @click="handleExport(scope.row)"
              class="oper-btn"
            >
             <el-icon>
               <Download />
             </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
      title="订单详情"
      v-model="detailDialogVisible"
      width="60%"
    >
      <el-descriptions column="1" border>
        <el-descriptions-item label="订单编号">{{ currentOrder.orderNo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="门店名称">{{ currentOrder.shopName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="时间">{{ 
          activeTab === 'receipt' ? currentOrder.receiptTime : currentOrder.salesTime || '-' 
        }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ currentOrder.contact || '-' }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentOrder.phone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="负责人">{{ currentOrder.manager || '-' }}</el-descriptions-item>
        <el-descriptions-item label="{{ activeTab === 'receipt' ? '收款金额' : '销售金额' }}">
          {{ activeTab === 'receipt' ? currentOrder.receiptAmount : currentOrder.salesAmount || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="{{ activeTab === 'receipt' ? '支付方式' : '产品类型' }}">
          {{ activeTab === 'receipt' ? currentOrder.paymentType : currentOrder.productType || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="{{ activeTab === 'receipt' ? '欠款金额' : '折扣金额' }}">
          {{ activeTab === 'receipt' ? currentOrder.arrears : currentOrder.discount || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">{{ currentOrder.status || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog
      title="编辑订单"
      v-model="editDialogVisible"
      width="60%"
    >
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="联系人">
          <el-input v-model="editForm.contact" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="editForm.manager" />
        </el-form-item>
        <!-- 修复 v-model 绑定问题：拆分条件渲染 -->
        <el-form-item v-if="activeTab === 'receipt'" label="支付方式">
          <el-input v-model="editForm.paymentType" />
        </el-form-item>
        <el-form-item v-if="activeTab === 'sales'" label="产品类型">
          <el-input v-model="editForm.productType" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editForm.status">
            <el-option label="待审核" value="待审核" />
            <el-option label="已审核" value="已审核" />
            <el-option label="已完成" value="已完成" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { Search, Download, ArrowLeft } from '@element-plus/icons-vue';

// 路由实例
const router = useRouter();

// 状态管理
const activeTab = ref('receipt');
const dateRange = ref([]);
const keyword = ref('');
const activePeriod = ref('today');

// 表格数据
const tableData = ref([]);

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 弹窗状态
const detailDialogVisible = ref(false);
const editDialogVisible = ref(false);
const currentOrder = ref({});
const editForm = reactive({
  contact: '',
  phone: '',
  manager: '',
  paymentType: '',
  productType: '',
  status: ''
});

// 状态样式映射
const statusTypeMap = {
  '待审核': 'warning',
  '已审核': 'success',
  '已冻结': 'danger',
  '已完成': 'primary'
};

// 初始化
onMounted(() => {
  initDateRange();
  fetchTableData();
});

// 初始化日期范围
const initDateRange = () => {
  const today = new Date().toISOString().split('T')[0];
  dateRange.value = [today, today];
};

// 切换标签
const switchTab = (tab) => {
  if (activeTab.value === tab) return;
  activeTab.value = tab;
  resetFilter();
  pagination.value.currentPage = 1;
  fetchTableData();
};

// 快捷周期切换
const handlePeriodChange = () => {
  const now = new Date();
  let start, end;

  if (activePeriod.value === 'today') {
    start = new Date(now.setHours(0, 0, 0, 0));
    end = new Date();
  } else if (activePeriod.value === 'week') {
    const day = now.getDay() || 7;
    start = new Date(now.setDate(now.getDate() - day + 1));
    start.setHours(0, 0, 0, 0);
    end = new Date();
  } else if (activePeriod.value === 'month') {
    start = new Date(now.getFullYear(), now.getMonth(), 1);
    start.setHours(0, 0, 0, 0);
    end = new Date();
  }

  dateRange.value = [
    start.toISOString().split('T')[0],
    end.toISOString().split('T')[0]
  ];
  
  fetchTableData();
};

// 获取表格数据
const fetchTableData = () => {
  const params = {
    type: activeTab.value,
    startDate: dateRange.value[0],
    endDate: dateRange.value[1],
    keyword: keyword.value,
    page: pagination.value.currentPage,
    pageSize: pagination.value.pageSize
  };

  setTimeout(() => {
    if (activeTab.value === 'receipt') {
      tableData.value = [
        {
          shopName: '东方美容院',
          receiptTime: '2024-11-11 09:23',
          orderNo: 'SK20241111001',
          contact: '张女士',
          phone: '13800138000',
          manager: '李经理',
          receiptAmount: '¥2980.00',
          paymentType: '微信支付',
          arrears: '¥0.00',
          status: '已审核'
        },
        {
          shopName: '丽人SPA馆',
          receiptTime: '2024-11-11 14:56',
          orderNo: 'SK20241111002',
          contact: '王女士',
          phone: '13900139000',
          manager: '张经理',
          receiptAmount: '¥5680.00',
          paymentType: '支付宝',
          arrears: '¥1000.00',
          status: '待审核'
        },
        {
          shopName: '名媛会所',
          receiptTime: '2024-11-10 16:30',
          orderNo: 'SK20241110005',
          contact: '刘女士',
          phone: '13700137000',
          manager: '赵经理',
          receiptAmount: '¥12980.00',
          paymentType: '银行转账',
          arrears: '¥0.00',
          status: '已冻结'
        }
      ];
      pagination.value.total = 28;
    } else {
      tableData.value = [
        {
          shopName: '东方美容院',
          salesTime: '2024-11-11 10:15',
          orderNo: 'XS20241111001',
          contact: '张女士',
          phone: '13800138000',
          manager: '李经理',
          salesAmount: '¥3580.00',
          productType: '套盒',
          discount: '¥300.00',
          status: '已完成'
        },
        {
          shopName: '丽人SPA馆',
          salesTime: '2024-11-11 15:20',
          orderNo: 'XS20241111002',
          contact: '王女士',
          phone: '13900139000',
          manager: '张经理',
          salesAmount: '¥6280.00',
          productType: '单品',
          discount: '¥500.00',
          status: '待审核'
        },
        {
          shopName: '名媛会所',
          salesTime: '2024-11-10 14:10',
          orderNo: 'XS20241110003',
          contact: '刘女士',
          phone: '13700137000',
          manager: '赵经理',
          salesAmount: '¥9800.00',
          productType: '仪器',
          discount: '¥1000.00',
          status: '已审核'
        }
      ];
      pagination.value.total = 42;
    }
  }, 500);
};

// 重置筛选条件
const resetFilter = () => {
  initDateRange();
  keyword.value = '';
  activePeriod.value = 'today';
};

// 编辑订单
const handleEdit = (row) => {
  if (row.status === '已冻结') {
    ElMessage.warning('已冻结订单不可编辑');
    return;
  }
  Object.assign(editForm, JSON.parse(JSON.stringify(row)));
  editDialogVisible.value = true;
};

// 保存编辑
const saveEdit = () => {
  const index = tableData.value.findIndex(item => item.orderNo === editForm.orderNo);
  if (index !== -1) {
    tableData.value[index] = { ...tableData.value[index], ...editForm };
    ElMessage.success('编辑成功');
    editDialogVisible.value = false;
  }
};

// 查看详情
const handleDetail = (row) => {
  currentOrder.value = row;
  detailDialogVisible.value = true;
};

// 冻结/解冻
const handleFreeze = (row) => {
  const isFreezing = row.status !== '已冻结';
  ElMessageBox.confirm(
    `${isFreezing ? '确定要冻结该订单吗？冻结后将无法编辑' : '确定要解冻该订单吗？'}`,
    '操作确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: isFreezing ? 'warning' : 'info'
    }
  ).then(() => {
    row.status = isFreezing ? '已冻结' : '待审核';
    ElMessage.success(`${isFreezing ? '冻结' : '解冻'}成功`);
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

// 导出
const handleExport = (row) => {
  ElMessage.success(`正在导出订单【${row.orderNo}】数据...`);
  setTimeout(() => {
    ElMessage.success(`订单【${row.orderNo}】导出成功`);
  }, 800);
};

// 分页处理
const handleSizeChange = (size) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1;
  fetchTableData();
};

const handlePageChange = (page) => {
  pagination.value.currentPage = page;
  fetchTableData();
};

// 合计计算
const calculateSummary = ({ columns, data }) => {
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    const prop = column.property;
    if (
      (activeTab.value === 'receipt' && ['receiptAmount', 'arrears'].includes(prop)) ||
      (activeTab.value === 'sales' && ['salesAmount', 'discount'].includes(prop))
    ) {
      const total = data.reduce((sum, item) => {
        const num = Number(item[prop].replace('¥', ''));
        return sum + (isNaN(num) ? 0 : num);
      }, 0);
      sums[index] = `¥${total.toFixed(2)}`;
    } else {
      sums[index] = '';
    }
  });
  return sums;
};

// 返回
const handleBack = () => {
  router.back();
};
</script>

<style scoped>
/* 样式与之前保持一致 */
.order-query-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
}

.tab-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 4px;
  padding: 0 10px;
  height: 48px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.tab-item {
  padding: 0 20px;
  height: 100%;
  line-height: 48px;
  cursor: pointer;
  font-size: 14px;
  position: relative;
}

.tab-item.active {
  color: #409eff;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #409eff;
}

.back-btn {
  margin-left: auto;
  color: #666;
}

.back-btn:hover {
  color: #409eff;
}

.filter-card {
  border: none;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.filter-item {
  display: flex;
  align-items: center;
}

.filter-label {
  font-size: 14px;
  color: #666;
  margin-right: 8px;
  white-space: nowrap;
}

.date-picker {
  width: 280px;
}

.keyword-input {
  width: 240px;
}

.filter-actions {
  margin-left: auto;
  display: flex;
  gap: 8px;
}

.quick-period {
  display: flex;
  align-items: center;
  padding-top: 10px;
  border-top: 1px dashed #eee;
}

.period-label {
  font-size: 14px;
  color: #666;
  margin-right: 12px;
  white-space: nowrap;
}

.table-card {
  border: none;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.oper-btn {
  margin-right: 5px;
  padding: 6px 12px;
  font-size: 14px;
}

.oper-btn:last-child {
  margin-right: 0;
}

.pagination-container {
  margin-top: 16px;
  text-align: right;
}

.el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-actions {
    margin-left: 0;
    width: 100%;
    justify-content: flex-start;
  }
  
  .date-picker, .keyword-input {
    width: 100%;
    max-width: 300px;
  }
  
  .pagination-container {
    text-align: center;
  }
}
</style>